
import sys
import time

from Page.BasePage import BasePage
from selenium import webdriver
from selenium.webdriver.common.by import By
from utils.log import logger


class LoginPage(BasePage):
    # 配置文件读取元素
    cms_url = BasePage.cf.getLocatorsOrAccount('LoginAccount', 'cms_url')
    # frame = BasePage.cf.getLocatorsOrAccount('LoginPage', 'frame')
    username = BasePage.cf.getLocatorsOrAccount('LoginPage', 'username')
    password = BasePage.cf.getLocatorsOrAccount('LoginPage', 'password')
    loginBtn = BasePage.cf.getLocatorsOrAccount('LoginPage', 'loginBtn')
    user_info = BasePage.cf.getLocatorsOrAccount('HomePage', 'user_info')  # 首页登录后用户信息

    def login(self, userName, passWord):
        """登录"""
        logger.info('-------staring login-------')
        self.loadUrl(self.cms_url)
        # self.switchToFrame(*LoginPage.frame)
        # self.clear(*LoginPage.username)
        self.sendKeys(*LoginPage.username, userName)
        # self.clear(*LoginPage.password)
        self.sendKeys(*LoginPage.password, passWord)
        self.click(*LoginPage.loginBtn)

        time.sleep(1)
        # self.screenshot('1.登录后截图')
        # logger.info('截图完成')

        # self.switchToDefaultFrame()
        logger.info('---------end login---------')

    def assertTextEqString(self, expected, name=None):
        """断言提示信息是否与期望的值相等"""

        try:
            tmp_tuple = ('class', 'login-form-wrap')
            login_form_wrap = self.findElement(*tmp_tuple)
            if login_form_wrap:
                pass
            else:
                logger.info('error to find element')
                assert False
            logger.info(f'tpye login_form_wrap = {type(login_form_wrap)}')
        except Exception as e:
            logger.info(f'error to find element, error: {e}')
            raise e
        else:
            eles = login_form_wrap.find_elements(webdriver.common.by.By.TAG_NAME, 'p')
            logger.info(f'len = {len(eles)}')
            text = ''
            for i in eles:
                if i.text != '':
                    logger.info(f'i.text = {i.text}')
                    text = i.text
            if text:
                assert text == expected, '{} ！= {}'.format(text, expected)
            else:
                assert False

    def assertLoginSuccess(self, expected, name=None):
        """断言判断是否登录成功"""
        ele = self.findElement(*LoginPage.user_info)
        if ele:
            text = self.getElementText(*LoginPage.user_info, name)
            logger.info('info: assert "{}" == "{}"'.format(text, expected))
            # logger.info(f'text = {text}, tpye = {type(text)}')
            # logger.info(f'expected = {expected}, tpye = {type(expected)}')
            assert str(text) == str(expected), '{} ！= {}'.format(text, expected)
        else:
            assert False

    def assert_login_button_exist(self, expect, name=None):
        """
        断言判断是否有登录按钮
        有登录按钮 → 登录失败 → 检查错误提示是否与期望一致
        没有 → 登录成功 → 检查用户信息是否与username一致
        """
        ele = self.findElement(*LoginPage.loginBtn)
        if ele:
            logger.info('登录按钮存在')
            # 有登录按钮, 则登录失败, 查找前端报错信息
            self.assertTextEqString(expect)
        else:
            # 没有登录按钮, 查找用户信息, 确认正常登录
            logger.info(f'登录按钮不存在, 查找用户信息栏\n')
            self.assertLoginSuccess(expect)


if __name__ == "__main__":
    # 测试代码

    from selenium import webdriver

    options = webdriver.ChromeOptions()
    options.add_experimental_option("excludeSwitches", ['enable-automation', 'load-extension'])  # 屏蔽自动化受控提示 && 开发者提示
    options.add_argument("--start-maximized")  # 浏览器启动时窗口最大化
    driver = webdriver.Chrome(options=options)
    # driver = webdriver.Firefox()
    login = LoginPage(driver, 10)
    login.login('11', '123456')
    time.sleep(3)
    driver.quit()
    # login.assert_login_button_exist('11')

    ele = driver.find_elements(By.CLASS_NAME, 'login-form-wrap')
    for i in ele:
        if i.is_displayed():
            i.click()
